<?php

use App\Admin\Form\Field\DistpickerNationwide;
use App\Admin\Form\Field\TimeRange;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid;
use Dcat\Admin\Form;
use Dcat\Admin\Grid\Filter;
use Dcat\Admin\Show;

/**
 * Dcat-admin - admin builder based on Laravel.
 * @author jqh <https://github.com/jqhph>
 *
 * Bootstraper for Admin.
 *
 * Here you can remove builtin form field:
 *
 * extend custom field:
 * Dcat\Admin\Form::extend('php', PHPEditor::class);
 * Dcat\Admin\Grid\Column::extend('php', PHPEditor::class);
 * Dcat\Admin\Grid\Filter::extend('php', PHPEditor::class);
 *
 * Or require js and css assets:
 * Admin::css('/packages/prettydocs/css/styles.css');
 * Admin::js('/packages/prettydocs/js/main.js');
 *
 */

use Dcat\Admin\Form\Field\Editor;
use Dcat\Admin\Support\JavaScript;

Editor::resolving(function (Editor $editor) {
    $ref = new \ReflectionClass(get_class($editor));
    $method = $ref->getMethod('defaultImageUploadUrl');
    $url = $method->invoke($editor);

//     设置默认配置
    $editor->options([
        'plugins' => [
            'advlist',
            'autolink',
            'link',
            'image',
            'media',
            'lists',
            'preview',
            'code',
            'help',
            'fullscreen',
            'table',
            'autoresize',
            'codesample',
            'axupimgs'
        ],
        'toolbar' => [
            'undo redo | preview fullscreen | styleselect | fontsizeselect bold italic underline strikethrough forecolor backcolor | link image media blockquote removeformat codesample',
            'alignleft aligncenter alignright  alignjustify| indent outdent bullist numlist table subscript superscript | code ｜ axupimgs',
        ],
        'images_upload_handler' =>JavaScript::make(
            <<<JS
                                  function (blobInfo, succFun, failFun) {
       var xhr, formData;
       var file = blobInfo.blob();
       xhr = new XMLHttpRequest();
       xhr.withCredentials = false;
       xhr.open('POST', "$url"); // 图片上传url
       xhr.onload = function() {
           var json;
           if (xhr.status != 200) {
               failFun('HTTP Error: ' + xhr.status);
               return;
           }
           json = JSON.parse(xhr.responseText);
           if (!json || typeof json.location != 'string') {
               failFun('Invalid JSON: ' + xhr.responseText);
               return;
           }
           succFun(json.location);
       };
       formData = new FormData();
       formData.append('file', file, file.name );
       xhr.send(formData);
   }
JS
        ), // 直接写会被当成字符串，而不是js函数
    ]);

});

Dcat\Admin\Form::extend('timeRangeC', TimeRange::class);
Dcat\Admin\Form::extend('distpickerNationwide', DistpickerNationwide::class);